<template>
  <div class="auth-form">
    <h2 class="form-title">创建账号</h2>
    <div class="input-group">
      <input 
        v-model="username" 
        type="text" 
        placeholder="用户名" 
        @keyup.enter="handleRegister"
      />
    </div>
    <div class="input-group">
      <input 
        v-model="password" 
        type="password" 
        placeholder="密码" 
        @keyup.enter="handleRegister"
      />
    </div>
    <button class="submit-btn" @click="handleRegister" :disabled="loading">
      <template v-if="!loading">注册</template>
      <LoadingIndicator v-else />
    </button>

    <!-- 状态提示 -->
    <Transition name="fade">
      <div v-if="error || success" class="status-message" :class="{ error, success }">
        <i class="status-icon">{{ error ? '✕' : '✓' }}</i>
        <span>{{ error || '注册成功' }}</span>
      </div>
    </Transition>

    <button class="switch-form-btn" @click="$emit('switch-form')">
      已有账号？点击登录
    </button>
  </div>
</template>

<script setup lang="ts">
import { ref } from 'vue'
import { useUserStore } from '@/stores/user'
import LoadingIndicator from './LoadingIndicator.vue'

const username = ref('')
const password = ref('')
const loading = ref(false)
const error = ref('')
const success = ref(false)

const userStore = useUserStore()

const props = defineProps({
  modalRef: {
    type: Object,
    required: true
  }
})

const resetForm = () => {
  username.value = ''
  password.value = ''
  error.value = ''
  success.value = false
  loading.value = false
}

const handleRegister = async () => {
  if (!username.value || !password.value) {
    error.value = '请填写用户名和密码'
    return
  }

  loading.value = true
  error.value = ''
  success.value = false

  try {
    const result = await userStore.registerUser(username.value, password.value)
    if (result.success) {
      success.value = true
      setTimeout(() => {
        resetForm()
        emit('switch-form')
      }, 1500)
    } else {
      error.value = result.message
    }
  } catch (err) {
    error.value = '注册失败，请稍后重试'
  } finally {
    loading.value = false
  }
}

const emit = defineEmits(['switch-form'])
defineExpose({ resetForm })
</script>

<style scoped lang="scss">
@import '@/styles/_auth-forms.scss';

.status-message {
  display: flex;
  align-items: center;
  gap: 8px;
  padding: 12px;
  border-radius: 8px;
  font-size: 14px;
  
  &.error {
    background: rgba(#ff4444, 0.1);
    color: #ff4444;
    border: 1px solid rgba(#ff4444, 0.2);
  }
  
  &.success {
    background: color-mix(in srgb, var(--hover-color) 10%, transparent);
    color: var(--hover-color);
    border: 1px solid color-mix(in srgb, var(--hover-color) 20%, transparent);
  }

  .status-icon {
    font-size: 16px;
    font-style: normal;
  }
}
</style>
